#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/11/18 3:17 PM
from django.conf import settings


class DFA:

    def __init__(self, message: str):
        self.root = {}
        [self.add_word(i) for i in message.split("|")]

    def add_word(self, word):
        children = self.root
        for i in range(len(word)):
            now_word = word[i]
            if not children:
                children[word[i]] = {}


            elif now_word not in children.keys():
                children[now_word] = {}

            children = children[now_word]
        children['flag'] = True

    def is_contain(self, message: str):
        message = message.replace("<br>", "\n")
        try:
            for i in range(len(message)):
                p = self.root
                j = i
                while j < len(message) and p is not None:
                    now_word = message[j]
                    if now_word in [" ", "\n"]:
                        j = j + 1
                    elif now_word in p.keys():
                        p = p[message[j]]
                        j = j + 1
                    else:
                        break

                if p.get("flag") is True:
                    return True
            return False
        except Exception as e:
            import logging
            logging.error("关键词出错")
            return False


text = getattr(settings, "PINGBICI",
               "王岐山|李克强|习近平|毛泽东|江泽民|六四|天安门事件|学生运动|习禁评|习包子|xi包子|维尼熊|泼墨|泼墨女孩|董瑶琼|泼墨事件|刘晓波|刘霞|零八宪章|08宪章|新疆集中营|再教育营|赵家人|大撒比|大撒币|赵老爷|刁近平|长者续命|红色权贵|你支|贵支|支那|小熊维尼|1984|郭文贵|萨格尔王|洗净平|73|七三|王山支山|菠菜|博彩|时时彩|彩票|百家乐|溜冰|冰毒|四号|嘎嘎|牙签|打K|打飞|打头|1766|金马奖")
pinbici = DFA(text)
